import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/motorcade_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_info_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_type_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/pages/vehicle_manage/vehicle_manage_controller.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BindVehicleController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  ScrollController scrollController = ScrollController();

  String driverId = "";

  //车辆归属
  String belongToType = "";
  String belongToName = "";

  //司机
  String motorcadeId = "";
  String motorcadeName = "";

  //车辆类型
  String vehicleType = "";
  String vehicleName = "";

  bool showBelongToTypeMenu = false;
  bool showMotorcadeMenu = false;
  bool showVehicleTypeMenu = false;

  List<BelongToType> belongToTypeList = [];
  List<VehicleTypeEntity> vehicleTypeList = [];
  List<MotorcadeEntity> motorcadeList = [];

  int page = 1;
  List<VehicleInfoItem> vehicleInfoList = [];
  int orderCount = 0;

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      driverId = arguments[Constant.PARAM_DRIVER_ID];
      motorcadeId = arguments[Constant.PARAM_MOTORCADE_ID];
      initBelongToTypeList();
      getVehicleInfoList();
    }
  }

  Future<void> goToAddVehiclePage() async {
    dynamic data = await Get.toNamed(Routes.addVehicle, arguments: {Constant.PARAM_IS_RETURN: true});
    if (data != null) {
      page = 1;
      multiState = MultiState.loading;
      update();
      getVehicleInfoList();
    }
  }

  Future<void> onRefresh() async {
    page = 1;
    getVehicleInfoList();
  }

  Future<void> onLoading() async {
    getVehicleInfoList();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getVehicleInfoList();
  }

  Future<void> getVehicleInfoList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_DRIVER_BIND_VEHICLE_INFO_LIST,
      {
        "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
        "driverId": driverId,
        "belongToType": belongToType.isNotEmpty ? belongToType : null,
        "type": vehicleType.isNotEmpty ? vehicleType : null,
        "motorcadeId": motorcadeId.isNotEmpty ? motorcadeId : null,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        VehicleInfoEntity vehicleInfoEntity = VehicleInfoEntity().fromJson(data);
        orderCount = vehicleInfoEntity.total ?? 0;
        List<VehicleInfoItem> list = vehicleInfoEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            vehicleInfoList.clear();
            refreshController.refreshCompleted();
            if (scrollController.hasClients) {
              scrollController.jumpTo(0);
            }
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            vehicleInfoList.clear();
          }
          vehicleInfoList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  Future<List<MotorcadeEntity>> getMotorcadeList() async {
    if (motorcadeList.isNotEmpty) {
      return motorcadeList;
    }
    HttpResult httpResult = await httpManager.post(Get.context, HttpAddress.GET_MOTORCADE_FILTER_LIST, {"superId": await SPUtils.getString(SPUtils.COMPANY_ID)}, isToast: true, isLoadingDialog: true);
    dynamic data = httpResult.data;
    if (data == null) {
      return [];
    }
    if (data is List) {
      motorcadeList = data.map((element) {
        return MotorcadeEntity().fromJson((element as Map<String, dynamic>));
      }).toList();
      MotorcadeEntity motorcadeEntity = MotorcadeEntity();
      motorcadeEntity.id = "";
      motorcadeEntity.name = "全部";
      motorcadeList.insert(0, motorcadeEntity);
      return motorcadeList;
    }
    return [];
  }

  void setSelectMotorcade(int? value) {
    showMotorcadeMenu = false;
    if (value != null) {
      String id = motorcadeList[value].id ?? "";
      motorcadeName = value != 0 ? (motorcadeList[value].name ?? "") : "全部车队";
      if (motorcadeId != id) {
        motorcadeId = id;
        page = 1;
        multiState = MultiState.loading;
        getVehicleInfoList();
      }
    }
    update();
  }

  Future<List<VehicleTypeEntity>> getVehicleType() async {
    if (vehicleTypeList.isNotEmpty) {
      return vehicleTypeList;
    }
    HttpResult httpResult = await httpManager.post(Get.context, HttpAddress.GET_VEHICLE_TYPE, {}, isToast: true, isLoadingDialog: true);
    dynamic data = httpResult.data;
    if (data == null) {
      return [];
    }
    if (data is List) {
      vehicleTypeList = data.map((element) {
        return VehicleTypeEntity().fromJson((element as Map<String, dynamic>));
      }).toList();
      VehicleTypeEntity vehicleTypeEntity = VehicleTypeEntity();
      vehicleTypeEntity.dictdataName = "全部";
      vehicleTypeEntity.dictdataValue = "";
      vehicleTypeList.insert(0, vehicleTypeEntity);
      return vehicleTypeList;
    }
    return [];
  }

  void setSelectVehicleType(int? value) {
    showVehicleTypeMenu = false;
    if (value != null) {
      String type = vehicleTypeList[value].dictdataValue ?? "";
      vehicleName = value != 0 ? vehicleTypeList[value].dictdataName ?? "" : "全部车型";
      if (vehicleType != type) {
        vehicleType = type;
        page = 1;
        multiState = MultiState.loading;
        getVehicleInfoList();
      }
    }
    update();
  }

  void setSelectBelongToType(int? value) {
    showBelongToTypeMenu = false;
    if (value != null) {
      String type = belongToTypeList[value].type;
      belongToName = value != 0 ? belongToTypeList[value].name : "全部归属";
      if (belongToType != type) {
        belongToType = type;
        page = 1;
        multiState = MultiState.loading;
        getVehicleInfoList();
      }
    }
    update();
  }

  void initBelongToTypeList() {
    belongToTypeList.add(BelongToType("全部", ""));
    belongToTypeList.add(BelongToType("自有", Constant.OWN_VEHICLE));
    belongToTypeList.add(BelongToType("外协", Constant.EXTERNAL_VEHICLE));
  }

  List<String> getSelectVehicleIdList() {
    List<String> list = [];
    if (vehicleInfoList.isEmpty) {
      return list;
    }
    vehicleInfoList.forEach((element) {
      if ((element.isSelect ?? false)) {
        list.add(element.id ?? "");
      }
    });
    return list;
  }

  void onConfirm() {
    List<String> vehicleIdList = getSelectVehicleIdList();
    if (vehicleIdList.isEmpty) {
      return;
    }
    httpManager.post(
      Get.context,
      HttpAddress.DRIVER_BIND_VEHICLE,
      {"driverId": driverId, "vehicleIds": vehicleIdList},
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("绑定失败");
            return;
          }
          ToastUtils.toast("绑定成功");
          Get.back(result: {});
        }
      },
    );
  }
}
